package com.linzx.markdown.processer.impl;

import com.intellij.ide.fileTemplates.impl.UrlUtil;
import com.linzx.markdown.processer.SourceNoteData;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avicomlin
 * @Description:
 * @date 2021/1/18
 */
public class ProcesserImpl extends AbstractProcesser {
    @Override
    protected Template getTemplate() throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        String path = UrlUtil.loadText(ProcesserImpl.class.getResource("/template/md.ftl"));
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        stringTemplateLoader.putTemplate("MDTemplate",path);
        configuration.setTemplateLoader(stringTemplateLoader);
        return configuration.getTemplate("MDTemplate");
    }

    @Override
    protected Object getModel(SourceNoteData data) {
        Map<String,Object> map = new HashMap<>();
        map.put("topic",data.getTopic());
        map.put("list",data.getData());
        return map;
    }

    @Override
    protected Writer getWriter(SourceNoteData data) throws Exception {
        String fileName = data.getFileName();
        File file = new File(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
        return bufferedWriter;
    }
}
